package com.lixinlei.tech.common.impl;

import com.lixinlei.tech.common.Codec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.CompressorOutputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.utils.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * apache编解码器实现
 *
 * @author yuwan
 */
@Slf4j
public class ApacheCodec implements Codec {
    private final String compressType;

    public ApacheCodec(String compressType) {
        this.compressType = compressType;
    }

    @Override
    public byte[] encode(byte[] content) {
        if (content == null || content.length == 0) {
            return content;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CompressorOutputStream encoder = null;
        try {
            encoder = new CompressorStreamFactory().createCompressorOutputStream(compressType, out);
            encoder.write(content);
        } catch (IOException | CompressorException e) {
            log.error("qunhe ApacheCodec encode error", e);
            return new byte[0];
        } finally {
            IOUtils.closeQuietly(encoder);
            IOUtils.closeQuietly(out);
        }
        return out.toByteArray();
    }

    @Override
    public byte[] decode(byte[] content) {
        if (content == null || content.length == 0) {
            return content;
        }
        ByteArrayInputStream in = new ByteArrayInputStream(content);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CompressorInputStream decoder = null;
        try {
            decoder = new CompressorStreamFactory().createCompressorInputStream(compressType, in);
            IOUtils.copy(decoder, out);
        } catch (IOException | CompressorException e) {
            log.error("qunhe ApacheCodec decode error", e);
            return new byte[0];
        } finally {
            IOUtils.closeQuietly(decoder);
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
        }
        return out.toByteArray();
    }
}
